#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: asyncio_download.py 
@version:
@time: 2023/04/18 
"""
import time
import aiohttp
import asyncio


async def download_one(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            print('Read {} from {}'.format(resp.content_length, url))


async def download_all(sites):
    tasks = [asyncio.create_task(download_one(site)) for site in sites]
    await asyncio.gather(*tasks, return_exceptions=True)


def main():
    sites = [
                'https://www.baidu.com',
            ] * 50
    start_time = time.perf_counter()
    """
    大佬总结, 总而言之是asyncio.run()会自动关闭循环,并且调用_ProactorBasePipeTransport.__del__报错, 
    而asyncio.run_until_complete()不会.
    """
    # asyncio.run(download_all(sites))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(download_all(sites))
    # loop.close()
    end_time = time.perf_counter()
    print('Download {} sites in {} seconds'.format(len(sites), end_time - start_time))


if __name__ == '__main__':
    main()
